using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Core;

namespace DaoGenerator
{
	public class DaoInterfaceFileGenerator
	{
		private const string DAO_DIRECTORY = @"GeneratedFiles\Model\Dao\";


		public DaoInterfaceFileGenerator() {}


		public DaoInterfaceFileGenerator(Assembly assembly)
		{
			this.Assembly = assembly;
		}


		public Assembly Assembly { get; set; }


		public void Execute(IEnumerable<string> selectedClassNames)
		{
			//read in the template
			TextReader reader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + @"\TemplateFiles\DaoInterfaceFile.template");

			string template = reader.ReadToEnd();

			TextWriter writer;

			foreach (string fullName in selectedClassNames) {
				//create a new template string
				string classTemplate = template;

				Type classType = this.Assembly.GetType(fullName);
				string className = classType.Name;

				string nameSpace = Utilities.GetDaoNameSpace(classType.Namespace);

				MemberInfo idMemberInfo = classType.GetMember("Id")[0];
				string idType = Utilities.GetRealTypeFromMemberProperty(idMemberInfo).Name;

				classTemplate = classTemplate.Replace("{SEARCH_NAME}", className.ToLower());
				classTemplate = classTemplate.Replace("{CLASS_NAME}", className);
				classTemplate = classTemplate.Replace("{NAMESPACE}", nameSpace);
				classTemplate = classTemplate.Replace("{ID_TYPE}", Utilities.GetCommonNameForType(idType));
				
				Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + DAO_DIRECTORY);

				writer = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + DAO_DIRECTORY + "I" + className + "Dao.cs");

				writer.Write(classTemplate);

				writer.Flush();
				writer.Close();
			}
		}

	}
}